import uuid
import platform
import hashlib
import subprocess
import os
from typing import Tuple


def get_mac_address() -> str:
    """获取 MAC 地址"""
    mac = uuid.getnode()
    return ':'.join(['{:02x}'.format((mac >> ele) & 0xff) for ele in range(40, -8, -8)])


def get_machine_serial() -> str:
    """获取主板或系统序列号（平台兼容）"""
    if os.name == 'nt':  # Windows
        try:
            output = subprocess.check_output("wmic baseboard get serialnumber", shell=True)
            return output.decode().split("\n")[1].strip()
        except Exception as e:
            return "unknown-windows"
    else:  # Linux / Mac
        try:
            if os.path.exists("/etc/machine-id"):
                with open("/etc/machine-id", 'r') as f:
                    return f.read().strip()
        except Exception as e:
            print(e)
        return "unknown-linux"


def generate_device_id() -> Tuple[str, str]:
    """生成绑定当前机器的唯一设备号"""
    mac = get_mac_address()
    serial = get_machine_serial()
    node = platform.node()  # 主机名
    sys_info = f"{mac}-{serial}-{node}"
    return sys_info, hashlib.sha256(sys_info.encode()).hexdigest()


if __name__ == '__main__':
    S, device_id = generate_device_id()
    print(S)
    # 30fe7b18674e0aaf6cac96e7e6f014e4aca22ab7b275158ee0763e6f6a511427
    print("当前设备唯一ID:", device_id)
